package com.circle.rest.modular.qrtz.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.circle.rest.core.util.SpringUtils;
import com.circle.rest.core.util.ToolUtil;
import com.circle.rest.modular.qrtz.model.Task;
import com.circle.rest.modular.qrtz.model.TaskRecord;
import com.circle.rest.modular.qrtz.service.ITaskRecordService;
import com.circle.rest.modular.qrtz.service.ITaskService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @program: RestfulApi
 * @description: 任务监听器
 * @author: 赵航
 * @create: 2019-04-12 17:12
 **/
public class GlobalJobListener implements JobListener {

    @SuppressWarnings("unchecked")
    private static ITaskService taskService = SpringUtils.getBean("taskService");
    @SuppressWarnings("unchecked")
    private static ITaskRecordService taskRecordService = SpringUtils.getBean("taskRecordService");

    @Override
    public String getName() {
        return getClass().getSimpleName();
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
//        String jobName = context.getJobDetail().getKey().getName();
//        System.out.println("[JOB]" + LocalDateTime.now() + jobName + " 即将执行 ");
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
//        String jobName = context.getJobDetail().getKey().getName();
//        System.out.println("[JOB]" + LocalDateTime.now() + jobName + " 被否决未被执行");
    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        String jobName = context.getJobDetail().getKey().getName();

        TaskRecord taskRecord = new TaskRecord();
        taskRecord.setCreateTime(LocalDateTime.now());
        taskRecord.setUpdateTime(LocalDateTime.now());
        if (ToolUtil.isNotEmpty(jobException)) {
            //失败
            taskRecord.setStatus(2);
            taskRecord.setErrorMsg(jobException.getMessage());
        }

        QueryWrapper<Task> wrapper = new QueryWrapper<>();
        wrapper.eq("name", jobName);
        List<Task> list = taskService.list(wrapper);
        if (list.size() > 0) {
            Task task = list.get(0);
            taskRecord.setTaskId(task.getId());
        }

        taskRecordService.save(taskRecord);
    }
}
